<?php

namespace app\admin\controller\user;


use app\admin\model\UserChangeType;
use app\admin\model\UserMoneyChange;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\db\Query;

/**
 * Class MoneyChange 会员流水
 * @package app\admin\controller\user
 * Author FashionJune
 * @ControllerAnnotation(title="流水管理")
 */
class MoneyChange extends AdminController
{

    protected $sort = [
        'id' => 'desc',
    ];

    protected $exWhere = ['user_id'];
    protected $allowModifyFields = ['remark'];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = UserMoneyChange::init();
    }

    /**
     * @NodeAnotation(title="资金流水")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where, $sort) = $this->buildTableParams();
            $count = $this->model
                ->with(['user', 'fromuser'])
                ->where($where)
                ->count();
            $list = $this->model
                ->with([
                    'user' => function (Query $query) {
                        $query->field(['id', 'nickname']);
                    },
                    'fromuser' => function (Query $query) {
                        $query->field(['id', 'nickname']);
                    },
                ])
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort + $sort)
                ->select();
            //处理信息
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID' => 'require',
            'field|字段' => 'require',
            'value|值' => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    public function typeList()
    {
        $data = UserChangeType::
        cache('change_type_list', 60)
            ->column('title', 'id');
        $this->success(null, $data);
    }

}
